package com.skytech.chatim.sky.xmlapi.command;



import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

/**
 * Created by Vega on 2015/1/7.
 */
public  class XmlApiCommandResult {

    public static final String SUCCESS = "SUCCESS";
    public static final String FAILURE = "FAILURE";

    private String result;
    private String exceptionId;
    private String xmlApiResponse;

    public Node getBodyNode() {
        return bodyNode;
    }

    private Node bodyNode ;

    public XmlApiCommandResult(String xmlApiResponse) {
        this.xmlApiResponse = xmlApiResponse;
    }

    public void parseResponse() throws DocumentException {
            Document document = DocumentHelper.parseText(xmlApiResponse);
            Node headerNode = document.selectSingleNode("/serv:message/serv:header");
            parseHeader(headerNode);
            if (SUCCESS.equals(result)) {
                 bodyNode =
                    document.selectSingleNode("/serv:message/serv:body/serv:bodyContent");
            }
    }

    protected void parseHeader(Node headerNode) {
        Node responseNode = headerNode.selectSingleNode("serv:response");
        result = SUCCESS.equals(responseNode.selectSingleNode("serv:result").getText()) ?
            SUCCESS :
            FAILURE;

        if (FAILURE.equals(result)) {
            Node exceptionIdNode = responseNode.selectSingleNode("serv:exceptionID");
            if (exceptionIdNode != null) {
                exceptionId = exceptionIdNode.getText();
            }
        }
    }


    public String getResult() {
        return result;
    }


    public String getExceptionId() {
        return exceptionId;
    }


    public boolean isSuccess() {
        return SUCCESS.equals(result);
    }
}
